package com.xxx.rpc.registry.redis;

import com.xxx.rpc.registry.ServiceRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;

/**
 * 基于 redis 的服务注册接口实现
 *
 * @Author: jc.huang
 * @Date: 2021/12/8
 */
public class RedisServiceRegistry implements ServiceRegistry {

    private static final Logger LOGGER = LoggerFactory.getLogger(RedisServiceRegistry.class);

    private Jedis jedis;

    public RedisServiceRegistry(String redisAddress) {
        //解析 ip 和 port
        String[] ipport = redisAddress.split(":");
        String ip = ipport[0];
        String port = ipport[1];

        jedis = new Jedis(ip, Integer.parseInt(port));
        LOGGER.debug("connect redis");
    }

    @Override
    public void register(String serviceName, String serviceAddress) {
        String key = Constant.PREFIX + serviceName;
        jedis.set(key, serviceAddress);
        LOGGER.debug("create redis key-value: {} => {}", key, serviceAddress);
    }
}
